package com.lgj.auth.code.customize.weChat;

import com.lgj.auth.code.customize.mobile.SmsVerificationCodeAuthenticationToken;
import com.lgj.common.constants.GrantTypeConstants;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author: guangjie.liao
 * @Date: 2023/08/27 21:10
 * @Description: 微信登陆授权者
 */
public class WeChatTokenGranter extends AbstractTokenGranter {
    private AuthenticationManager authenticationManager;

    public WeChatTokenGranter(AuthorizationServerTokenServices tokenServices,
                                           ClientDetailsService clientDetailsService,
                                           OAuth2RequestFactory requestFactory,
                                           AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, GrantTypeConstants.WE_CHAT);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap(tokenRequest.getRequestParameters());

        //微信授权码
        String code = parameters.get("code");
        parameters.remove("code");

        Authentication userAuth = new WeChatAuthenticationToken(null, code);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        try {
            userAuth = this.authenticationManager.authenticate(userAuth);
        } catch (AccountStatusException var8) {
            throw new InvalidGrantException(var8.getMessage());
        } catch (BadCredentialsException var9) {
            throw new InvalidGrantException(var9.getMessage());
        }

        if (userAuth != null && userAuth.isAuthenticated()) {
            OAuth2Request storedOAuth2Request = this.getRequestFactory().createOAuth2Request(client, tokenRequest);
            return new OAuth2Authentication(storedOAuth2Request, userAuth);
        } else {
            throw new InvalidGrantException("Could not authenticate user: " + code);
        }
    }
}
